<script setup lang="ts">
import { createEnterpriseAPI, getIndustryListAPI, uploadAPI } from '@/apis/enterprise';
import type { Industry } from '@/types/enterprise';
import { ElMessage, type FormInstance, type FormItemInstance, type FormRules, type UploadInstance, type UploadRawFile, type UploadRequestOptions } from 'element-plus';

import { reactive, ref } from 'vue';
import { useRouter } from 'vue-router';
const industryList = ref<Industry[]>([]) // 可选行业列表
const getIndustryList = async () => {
  const res = await getIndustryListAPI()
  industryList.value = res.data
}
getIndustryList()

const addForm = reactive({
  name: '', // 企业名称
  legalPerson: '', // 法人
  registeredAddress: '', // 注册地址
  industryCode: '', // 所在行业
  contact: '', // 企业联系人
  contactNumber: '', // 联系人电话
  businessLicenseUrl: '', // 营业执照url
  businessLicenseId: '' // 营业执照id
})
const addFormRules = ref<FormRules<typeof addForm>>({
  name: [
    { required: true, message: '请输入企业名称', trigger: 'blur' },
  ],
  legalPerson: [
    { required: true, message: '请输入法人', trigger: 'blur' },
  ],
  registeredAddress: [
    { required: true, message: '请输入注册地址', trigger: 'blur' },
  ],
  industryCode: [
    { required: true, message: '请选择所在行业', trigger: 'change' },
  ],
  contact: [
    { required: true, message: '请输入联系人', trigger: 'blur' },
  ],
  contactNumber: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3456789]\d{9}$/, message: '请输入正确的联系电话', trigger: 'blur' }
  ],
  businessLicenseUrl: [
    { required: true, message: '请上传营业执照', trigger: 'blur' },
  ]
  // businessLicenseId: [
  //   { required: true, message: '请上传营业执照', trigger: 'blur' },
  // ]
})
const addFormRef = ref<FormInstance>()
const router = useRouter()
const isLoading = ref(false)
//统一校验
const onSubmit = async () => {
  try {
    // 统一表单校验
    await addFormRef.value?.validate();
    isLoading.value = true
    await createEnterpriseAPI(addForm)
    // 返回列表页
    router.back()
  } catch (error) {
    ElMessage.error("请按要求完善企业信息");
  } finally {
    isLoading.value = false
  }
};
const uploadRequest = async (options: UploadRequestOptions) => {
  // console.log(options);
  // 准备 fromData 对象
  const fromData = new FormData();
  // 文件
  fromData.append("file", options.file);
  // 上传类型
  fromData.append("type", "businessLicense");
  const res = await uploadAPI(fromData);
  // 保存营业执照 id 和 url
  addForm.businessLicenseId = res.data.id
  addForm.businessLicenseUrl = res.data.url
  // console.log("文件上传成功", res);
  // 主动触发校验(校验通过，错误提示就会消失)
  addFormRef.value?.validateField('businessLicenseUrl')
}
const uploadRef = ref<UploadInstance>();
// 重置表单
const onReset = () => {
  // 清空 url
  addForm.businessLicenseUrl = "";
  // 重置常规表单
  addFormRef.value?.resetFields();
  // 重置清空已上传的文件列表
  uploadRef.value?.clearFiles();
};
const beforeUpload = async (rawFile: UploadRawFile) => {
  console.log(rawFile);
  const imageSize = 5 * 1024 * 1024
  const imageType = ['image/jpeg', 'image/png', 'image/jpg']
  if (imageSize < rawFile.size) {
    ElMessage.warning({ message: '文件过大，请上传小于5M的图片', type: 'warning' })
    return false
  } else if (imageType.includes(rawFile.type) == false) {
    ElMessage.error('文件类型错误,仅支持jpg/png/jpeg扩展名的文件')
    return false
  }
}
//移除文件
const onFileRemove = () => {
  // 清空营业执照信息
  addForm.businessLicenseId = "";
  addForm.businessLicenseUrl = "";
}
</script>


<template>
  <div class="add-enterprise">
    <header class="add-header">
      <el-page-header content="添加企业" @back="$router.back()" />
    </header>
    <main class="add-main">
      <div class="form-container">
        <div class="title">企业信息</div>
        <div class="form">
          <el-form ref="addFormRef" label-width="100px" :model="addForm" :rules="addFormRules">
            <el-form-item label="企业名称" prop="name">
              <el-input v-model="addForm.name" clearable />
            </el-form-item>
            <el-form-item label="法人" prop="legalPerson">
              <el-input v-model="addForm.legalPerson" clearable />
            </el-form-item>
            <el-form-item label="注册地址" prop="registeredAddress">
              <el-input v-model="addForm.registeredAddress" clearable />
            </el-form-item>
            <el-form-item label="所在行业" prop="industryCode">
              <el-select v-model="addForm.industryCode" clearable>
                <el-option v-for="item in industryList" :key="item.industryCode" :value="item.industryCode"
                  :label="item.industryName" />
              </el-select>
            </el-form-item>
            <el-form-item label="企业联系人" prop="contact">
              <el-input v-model="addForm.contact" clearable />
            </el-form-item>
            <el-form-item label="联系电话" prop="contactNumber">
              <el-input v-model="addForm.contactNumber" clearable />
            </el-form-item>
            <el-form-item label="营业执照" prop="businessLicenseUrl">
              <el-upload drag name="file" :http-request="uploadRequest" accept=".png,.jpg,.jpeg"
                :before-upload="beforeUpload" :on-remove="onFileRemove"
                ref="uploadRef" :limit="1">
                <template #trigger>
                  <el-button size="small" type="primary">点击上传</el-button>
                </template>
                <template #tip>
                  <div class="el-upload__tip">只能上传jpg/png文件，且不超过5M</div>
                </template>
              </el-upload>
            </el-form-item>

          </el-form>
        </div>
      </div>
    </main>
    <footer class="add-footer">
      <div class="btn-container">
        <el-button @click="onReset">重置</el-button>
        <el-button :loading="isLoading" type="primary" @click="onSubmit">确定</el-button>
      </div>
    </footer>
  </div>
</template>


<style scoped lang="scss">
.add-enterprise {
  background-color: #f4f6f8;
  height: 100vh;

  .add-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 20px;
    height: 64px;
    line-height: 64px;
    font-size: 16px;
    font-weight: bold;
    background-color: #fff;

    .left {
      span {
        margin-right: 4px;
      }

      .arrow {
        cursor: pointer;
      }
    }

    .right {
      text-align: right;
    }
  }

  .add-main {
    background: #f4f6f8;
    padding: 20px 130px;

    .form-container {
      background-color: #fff;

      .title {
        height: 60px;
        line-height: 60px;
        padding-left: 20px;
      }

      .form {
        margin-bottom: 20px;
        padding: 20px 65px 24px;

        .el-form {
          display: flex;
          flex-wrap: wrap;

          .el-form-item {
            width: 50%;
          }
        }
      }
    }
  }

  .add-footer {
    position: fixed;
    bottom: 0;
    width: 100%;
    padding: 24px 50px;
    color: #000000d9;
    font-size: 14px;
    background: #fff;
    text-align: center;
  }
}
</style>